package com.free.compilation.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.free.common.core.utils.DateUtils;
import com.free.compilation.domain.ZoneCompilationChapter;
import com.free.compilation.domain.ZoneCompilationStep;
import com.free.compilation.mapper.ZoneCompilationChapterMapper;
import com.free.compilation.mapper.ZoneCompilationStepMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * 章节记录Service业务层处理
 *
 * @author free
 * @date 2023-11-17
 */
@Service
public class ZoneCompilationChapterService extends ServiceImpl<ZoneCompilationChapterMapper, ZoneCompilationChapter> {
    @Autowired
    private ZoneCompilationChapterMapper zoneCompilationChapterMapper;
    @Autowired
    private ZoneCompilationStepMapper zoneCompilationStepMapper;

    /**
     * 查询章节记录
     *
     * @param id 章节记录主键
     * @return 章节记录
     */
    public ZoneCompilationChapter selectZoneCompilationChapterById(Long id) {
        return zoneCompilationChapterMapper.selectById(id);
    }

    /**
     * 查询章节记录列表
     *
     * @param zoneCompilationChapter 章节记录
     * @return 章节记录
     */
    public List<ZoneCompilationChapter> selectZoneCompilationChapterList(ZoneCompilationChapter zoneCompilationChapter) {
        QueryWrapper<ZoneCompilationChapter> chapterQueryWrapper = new QueryWrapper<>(zoneCompilationChapter).orderBy(true, true, "sort");
        chapterQueryWrapper.eq("deleted", 0);
        List<ZoneCompilationChapter> zoneCompilationChapters = zoneCompilationChapterMapper.selectList(chapterQueryWrapper);
        zoneCompilationChapters.forEach(e -> {
            QueryWrapper<ZoneCompilationStep> stepQueryWrapper = new QueryWrapper<>();
            stepQueryWrapper.eq("chapter_id", e.getId());
            stepQueryWrapper.eq("deleted",0);
            stepQueryWrapper.orderBy(true, true, "sort");
            e.setZoneCompilationSteps(zoneCompilationStepMapper.selectList(stepQueryWrapper));
        });

        return zoneCompilationChapters;
    }

    /**
     * 新增章节记录
     *
     * @param zoneCompilationChapter 章节记录
     * @return 结果
     */
    public ZoneCompilationChapter insertZoneCompilationChapter(ZoneCompilationChapter zoneCompilationChapter) {

        if (!ObjectUtil.isNotEmpty(zoneCompilationChapter.getId())){
            //获取当前的最大值排序值
            QueryWrapper<ZoneCompilationChapter> maxSort = new QueryWrapper();
            maxSort.select("MAX(sort) sort")
                    .eq(!ObjectUtils.isEmpty(zoneCompilationChapter.getCompilationId()), "compilation_id", zoneCompilationChapter.getCompilationId());
            ZoneCompilationChapter maxSortStep = zoneCompilationChapterMapper.selectOne(maxSort);
            if (ObjectUtil.isEmpty(maxSortStep)){
                zoneCompilationChapter.setSort(1L);
            }else {
                zoneCompilationChapter.setSort(maxSortStep.getSort()+1);
            }
            this.save(zoneCompilationChapter);
        }else {
            this.updateById(zoneCompilationChapter);
        }
        List<ZoneCompilationStep> noteList = zoneCompilationChapter.getNoteList();

        if (!ObjectUtils.isEmpty(noteList)) {
            HashSet<Long> set = new HashSet<>();
            noteList.forEach(e -> set.add(e.getNoteId()));
            Assert.isTrue(noteList.size() == set.size(),"有重复数据，请检查~");
            //删除以前的
            ZoneCompilationStep deleteStep = new ZoneCompilationStep();
            deleteStep.setCompilationId(zoneCompilationChapter.getCompilationId());
            deleteStep.setChapterId(zoneCompilationChapter.getId());
            this.zoneCompilationStepMapper.delete(new QueryWrapper<>(deleteStep));
            for (int i = 0; i < noteList.size(); i++) {
                ZoneCompilationStep zoneNote = noteList.get(i);
                ZoneCompilationStep zoneCompilationStep = new ZoneCompilationStep();
                zoneCompilationStep.setCompilationId(zoneCompilationChapter.getCompilationId());
                zoneCompilationStep.setChapterId(zoneCompilationChapter.getId());
                zoneCompilationStep.setNoteId(zoneNote.getNoteId());
                zoneCompilationStep.setSort((long) (i + 1));
                this.zoneCompilationStepMapper.insert(zoneCompilationStep);
            }
        }

        return zoneCompilationChapter;
    }

    /**
     * 修改章节记录
     *
     * @param zoneCompilationChapter 章节记录
     * @return 结果
     */
    public int updateZoneCompilationChapter(ZoneCompilationChapter zoneCompilationChapter) {
        zoneCompilationChapter.setUpdateTime(DateUtils.getNowDate());
        return zoneCompilationChapterMapper.updateById(zoneCompilationChapter);
    }

    /**
     * 批量删除章节记录
     *
     * @param ids 需要删除的章节记录主键
     * @return 结果
     */
    public int deleteZoneCompilationChapterByIds(Long[] ids) {

        Arrays.stream(ids).forEach(e -> {
            QueryWrapper<ZoneCompilationStep> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("chapter_id", e);
            Long aLong = zoneCompilationStepMapper.selectCount(queryWrapper);
            Assert.isTrue(aLong == 0, "段落下有记录，请先删除记录~");
        });
        return zoneCompilationChapterMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除章节记录信息
     *
     * @param id 章节记录主键
     * @return 结果
     */
    public int deleteZoneCompilationChapterById(Long id) {
        return zoneCompilationChapterMapper.deleteById(id);
    }

    public int batchUpdateChapter(List<ZoneCompilationChapter> zoneCompilationChapter) {
        if (ObjectUtils.isEmpty(zoneCompilationChapter)) {
            return 0;
        }
        int count = 0;
        for (int i = 0; i < zoneCompilationChapter.size(); i++) {
            ZoneCompilationChapter chapter = zoneCompilationChapter.get(i);
            chapter.setSort((long) (i + 1));
            this.zoneCompilationChapterMapper.updateById(chapter);
            count++;
        }
        return count;
    }
}
